<?php
namespace app\event;
use app\service\model\AddonModel;
use think\facade\Db;
use think\facade\Lang;
use think\facade\Event;
use think\facade\Cache;
class InitAddon {

    /**
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function handle() {
        $this->initEvent();
    }

    /**
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    private function InitEvent() {
        $listen_array = Cache::get("addon_event_list");

        if(!$listen_array) {
            // 获取已安装的插件列表
            $addon_data = Db::name('addon')->column('name');
            $listen_array = [];
            foreach ($addon_data as $k => $addon) {
                $addon_event = require_once root_path() . '/addon/' . $addon . '/config/event.php';
                $listen = isset($addon_event['listen']) ? $addon_event['listen'] : [];
                if($listen) {
                    $listen_array[] = $listen;
                }
            }
            Cache::tag("addon")->set("addon_event_list", $listen_array);
        }

        if($listen_array) {
            foreach ($listen_array as $k => $listen) {
                if($listen) {
                    // 动态绑定插件事件
                    Event::listenEvents($listen);
                }
            }
        }
    }
}